import requests
import json
import time

# 定义服务器的URL和端口
SERVER_URL = 'http://localhost:5000'
TRAINING_ROUTE = '/start_training'


# 定义客户端发送请求的函数
def send_training_request(task_id):
    # 构建请求的JSON数据
    payload = {
        #'taskid': task_id
    }
    # 发送POST请求到服务器的/trainning路由
    response = requests.post(f"{SERVER_URL}{TRAINING_ROUTE}", json=payload)

    # 检查响应状态码
    if response.status_code == 200:
        print(f"Training task {task_id} started successfully.")
        print(response.json())
    else:
        print(response.json())
        print(f"Failed to start training task {task_id}. Status code: {response.status_code}")

from datetime import datetime
# 主函数，用于运行客户端
def open_task_file(task_id):
    # 假设我们知道训练结果文件存储在当前目录下的training_results文件夹中
    result_file_path = f"training_tasks/{task_id}/training_result.txt"

    print('读取',result_file_path)
    try:
        with open(result_file_path, 'r') as result_file:
            print(result_file.read())
    except FileNotFoundError:

        print(f"Result file {result_file_path} for task {task_id} 没找到.")

def main():
    # 定义一个任务ID
    timestamp = datetime.now().strftime('%Y%m%d_%H_%M_%S')
    task_id = '12345_'+timestamp

    # 发送训练请求
    send_training_request(task_id)

    # 等待训练完成（这里简单地等待5秒，实际应用中可能需要根据实际情况调整）
    time.sleep(7)

    # 检查训练结果
    print(f"Checking training results for task {task_id}...")
    open_task_file(task_id)

if __name__ == "__main__":
    main()
    # task_id = '12345_20240404_16_55_29'
    # open_task_file(task_id)